package colaborativo.ondefica;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.util.GeoPoint; 
import org.osmdroid.api.IMapController;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.bonuspack.overlays.Marker.OnMarkerDragListener;
import org.osmdroid.bonuspack.routing.MapQuestRoadManager;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.PathOverlay;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.Toast;

public class Osm_maps extends Activity implements OnClickListener {

	// Osm Map
    private MapView osmMap;
    private IMapController osmController;
    List<Overlay> mapOverlays;  
    Drawable drawable;  
    MyItemizedOverlay itemizedOverlay; 
    long tp_prs, ini_prs; 
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_osm_maps);
        
        Button btn = (Button) findViewById(R.id.button1);
		btn.setOnClickListener(this);						
		
		try {
            initilizeMap();
            
 
        } catch (Exception e) {
            e.printStackTrace();
        }	
    }
    
    private ArrayList<JSONObject> pontosVisiveis(){
    	Projection prj = osmMap.getProjection();
    	GeoPoint nordeste = (GeoPoint) prj.getNorthEast(), sudoeste = (GeoPoint) prj.getSouthWest(); 
    	Log.d("Debug", nordeste.toString()+" / "+sudoeste.toString());
    	//Modelo INSERT INTO `u763685312_fb`.`geoPonto` (`nomeLocal`, `latitute`, `longitude`) VALUES ('teste1', '-3081208', '-59968357'), ('teste2', '-3097278', '-59950717');
    	//Procedimento de Querys
		String qry= "SELECT * FROM `geoPonto` WHERE `latitute`>= "+ sudoeste.getLatitudeE6() +" AND `latitute`<= "
				+ nordeste.getLatitudeE6() +" AND `longitude`>= "+sudoeste.getLongitudeE6()+" AND `longitude`<= "
				+nordeste.getLongitudeE6();
		boolean retornoQry = false; 
		Log.d("Query", qry);
		JSONArray jSarr=null;		
		jSarr = DbConnection.consulta(qry);
				
		while(jSarr==null);
		ArrayList<JSONObject> result = null;
				
		for(int i=0; i<jSarr.length();i++){
			try {
				Log.d("Result", jSarr.getJSONObject(i).get("nomeLocal").toString());
				Integer lat = Integer.valueOf(jSarr.getJSONObject(i).get("latitute").toString());
				Integer lon = Integer.valueOf(jSarr.getJSONObject(i).get("longitude").toString());
				JSONObject json=  new JSONObject();
				json.put("Local", jSarr.getJSONObject(i).get("nomeLocal").toString());
				json.put("Ponto", new GeoPoint(lat,lon));
				result.add(json);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
    	
		return result;    	
    }
    
    private void carregarMarcadores() throws JSONException{
    	ArrayList<JSONObject> gPs = pontosVisiveis();
    	Log.d("ResultadosMarcadoresGeral", gPs.toString());
        for(JSONObject Pts:gPs){
            Marker startMarker = new Marker(osmMap);
    		startMarker.setPosition((GeoPoint)Pts.get("Ponto"));
    		startMarker.setAnchor(Marker.ANCHOR_CENTER, 1.0f);
    		Log.d("ResultadosMarcadores", Pts.getString("Local"));
    		startMarker.setTitle(Pts.getString("Local"));
    		//startMarker.setIcon(getResources().getDrawable(R.drawable.marker_kml_point).mutate());
    		//startMarker.setImage(getResources().getDrawable(R.drawable.ic_launcher));
    		//startMarker.setInfoWindow(new MarkerInfoWindow(R.layout.bonuspack_bubble_black, map));
    		startMarker.setDraggable(true);
    		startMarker.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());
    		osmMap.getOverlays().add(startMarker);
        }
    }
    
//ponto inicio-fim -3.08988/-59.96550  ----------  -3.08854/-59.96455
    private void initilizeMap() {
        
    	osmMap = (MapView) findViewById(R.id.omsmapview);
    	osmMap.setTileSource(TileSourceFactory.MAPNIK);
    	osmMap.setBuiltInZoomControls(true);
    	osmMap.setMultiTouchControls(true);
    	osmController = osmMap.getController();        	
    	        		        	        			        			               	
    	osmController.setZoom(10);
    	osmController.setCenter(new GeoPoint(-3.08923,-59.96453));
    	//osmController.animateTo(new GeoPoint(-3.08923,-59.96453));        	        
        // check if map is created successfully or not
        if (osmMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }else{        	
        	
			 RoadManager roadManager = new MapQuestRoadManager("Fmjtd%7Cluur216ynd%2C25%3Do5-90tlla");
			 roadManager.addRequestOption("routeType=fastest");
			 ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
			 waypoints.add(new GeoPoint(-3.09105,-59.96556));
			 waypoints.add(new GeoPoint(-3.10014,-59.97481)); //end point                 
			 Road road = roadManager.getRoad(waypoints);
			 PathOverlay roadOverlay = RoadManager.buildRoadOverlay(road, this);
			 osmMap.getOverlays().add(roadOverlay);
			 osmMap.invalidate();
			 try {
				carregarMarcadores();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }        
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.osm_maps, menu);
        return true;
    }
    
    @Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.button1:
			Toast.makeText(getApplicationContext(),"Toast that OSMmap", Toast.LENGTH_SHORT).show();
			break;
		case R.id.toggleButton1:
			break;		
		}
	}
    
    class OnMarkerDragListenerDrawer implements OnMarkerDragListener {
		ArrayList<GeoPoint> mTrace = new ArrayList<GeoPoint>(200);
		@Override public void onMarkerDrag(Marker marker) {
			mTrace.add(marker.getPosition());
		}
		@Override public void onMarkerDragEnd(Marker marker) {
			Polyline p = new Polyline(osmMap.getContext());
			p.setColor(0xAA0000FF);
			p.setWidth(2.0f);
			p.setPoints(mTrace);
			osmMap.getOverlays().add(p);
			osmMap.invalidate();
		}
		@Override public void onMarkerDragStart(Marker marker) {
			mTrace.add(marker.getPosition());
		}
	}
 /*   
  //Customized  MyItemizedOverlay class  
    class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {  
	    //Define an OverlayItem ArrayList, in which we'll put each of  
	    // the OverlayItem objects we want on our map  
	    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();  
	      
	    public MyItemizedOverlay(Drawable defaultMarker) {  
		    // Wrap this around our defaultMarker  
		    super(boundCenterBottom(defaultMarker));  
		    // TODO Auto-generated constructor stub  
	    }  
	      
	    // Get ArrayList items  
	    @Override  
	    protected OverlayItem createItem(int i) {  
		    // TODO Auto-generated method stub  
		    return mOverlays.get(i);  		     
	    }  
	      
	    // return OverlayItem size  
	    @Override  
	    public int size() {  
		    // TODO Auto-generated method stub  
		    return mOverlays.size();  
	    }  
	      
	    // Show the locations message  
	    @Override  
	    protected boolean onTap(int index) {  
		    OverlayItem item = mOverlays.get(index);  
		    // Title  
		    String title = item.getTitle();  
		    // Snippet  
		    String snippet = item.getSnippet();  
		    Toast.makeText(MapViewDemoActivity.this, title + "\n" + snippet,  
		    Toast.LENGTH_LONG).show();  
		    return true;  
	    }  
	      
	    // Define a method in order to add new OverlayItems to our ArrayList  
	    public void addOverlay(OverlayItem overlay) {  
		    // add OverlayItems  
		    mOverlays.add(overlay);  
		    // populate  
		    populate();  
	    }  
 	}  */
}
